const config = require('../config');
const { mongoose } = require('../db');

const schema = mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User',
        autopopulate: true,
    },
    title: {
        type: String,
        required: true,
        max: 100,
        trim: true,
        index: true, // 添加索引
    },
    content: {
        type: String,
        required: true,
        trim: true,
    },
    desc: {
        type: String,
        trim: true,
        max: 300,
    },
    cover: {
        type: String,
        trim: true,
        default: config.defaultCover,
    },
    deletedAt: { type: Date, default: null },
}, {
    timestamps: true,
    // 虚拟字段数据显示
    toJSON: { virtuals: true },
    toObject: { virtuals: true }
});

// 关联创建虚拟字段like、comment、favorite、share、view。
schema.virtual('viewCount', {
    ref: "View",
    localField: "_id",
    foreignField: 'article',
    count: true
})
schema.virtual('likeCount', {
    ref: 'Like',
    localField: '_id',
    foreignField: 'article', // 通过articleId关联Like表
    count: true
});

schema.virtual('commentCount', {
    ref: 'Comment',
    localField: '_id',
    foreignField: 'article', // 通过articleId关联Comment表
    count: true
});

schema.virtual('favoriteCount', {
    ref: 'Favorite',
    localField: '_id',
    foreignField: 'article', // 通过articleId关联Favorite表
    count: true
});

schema.virtual('shareCount', {
    ref: 'Share',
    localField: '_id',
    foreignField: 'article', // 通过articleId关联Share表
    count: true
});

schema.plugin(require('mongoose-autopopulate'));

module.exports = mongoose.model('Article', schema, 'article');